package com.tjl.foodapp;

import static android.app.Activity.RESULT_OK;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.tjl.foodapp.utils.ImageUploadTask;
import com.tjl.foodapp.utils.OkHttpClientUtil;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link MeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MeFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public MeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MeFragment newInstance(String param1, String param2) {
        MeFragment fragment = new MeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    EditText et_username_me,et_password_me,et_phone_me,et_address_me;
    Button btn_ok_me;
    RadioGroup radioGroup;
    RecyclerView rv_order_bottom;
    TextView tx_userid_me;
     //上下文
   public static  Context context;
    //请求队列
   public static RequestQueue queue;
    //子页面管理器
    FragmentManager manager;
    //头像
    ImageButton btn_adv;
    //数据源
   public static ArrayList<Order> orderList = new ArrayList<Order>();
   public static ArrayList<Order> pinglunList = new ArrayList<Order>();
    class MyOrderAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view =  LayoutInflater.from(context).inflate(R.layout.done_order_item,null);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
           ViewHolder viewHolder = (ViewHolder)holder;
            Order order = orderList.get(position);
            setItemPriceByURL(Utils.urlBase+"and_getFoodByFoodId.do?id="+order.getFood_id()
                    ,order,viewHolder);
            viewHolder.btn_pinglun.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AddCommentFragment fragment = new AddCommentFragment();
                    Bundle bundle = new Bundle();
                    bundle.putInt("order_id",order.getOrder_id());
                    bundle.putString("type","add");
                    fragment.setArguments(bundle);
                    fragment.show(manager,"addComment");
                }
            });
            if(order.getContent()!=null&&!order.getContent().equals("")){
                viewHolder.btn_pinglun.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return orderList.size();
        }
        class ViewHolder extends RecyclerView.ViewHolder{
           TextView tx_foodname_order_doneorder,tx_shop_doneorder;
           Button btn_pinglun;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
               tx_foodname_order_doneorder = itemView.findViewById(R.id.tx_foodname_order_doneorder);
               tx_shop_doneorder = itemView.findViewById(R.id.tx_shop_doneorder);
               btn_pinglun = itemView.findViewById(R.id.btn_pinglun);

            }
        }
    }
    class MyPinglunAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view =  LayoutInflater.from(context).inflate(R.layout.done_pinglun_item,null);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            ViewHolder viewHolder = (ViewHolder)holder;
            Order order = pinglunList.get(position);
           viewHolder.tx_content_donepinglun.setText(order.getContent()+" "+
                   "("+order.getComment_time_str()+")");
           setItemFoodMsg(Utils.urlBase+"and_getFoodByFoodId.do?id="+order.getFood_id(),viewHolder);
           viewHolder.btn_update_donepinglun.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   Bundle bundle = new Bundle();
                   bundle.putInt("order_id",order.getOrder_id());
                   bundle.putString("type","update");
                   bundle.putString("content",order.getContent());
                   AddCommentFragment fragment = new AddCommentFragment();
                   fragment.setArguments(bundle);
                   fragment.show(manager,"updatepinglun");
               }
           });
           viewHolder.btn_delete_donepinglun.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                 deletePinglunByURL(Utils.urlBase+"and_deletePinglunById.do?id="+order.getOrder_id());
               }
           });
        }

        @Override
        public int getItemCount() {
            return pinglunList.size();
        }
        class ViewHolder extends RecyclerView.ViewHolder{
           TextView tx_content_donepinglun,tx_food_donepinglun,tx_shop_donepinglun;
           Button btn_update_donepinglun,btn_delete_donepinglun;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                tx_content_donepinglun = itemView.findViewById(R.id.tx_content_donepinglun);
                tx_food_donepinglun = itemView.findViewById(R.id.tx_food_donepinglun);
                tx_shop_donepinglun = itemView.findViewById(R.id.tx_shop_donepinglun);
                btn_update_donepinglun = itemView.findViewById(R.id.btn_update_donepinglun);
                btn_delete_donepinglun = itemView.findViewById(R.id.btn_delete_donepinglun);
            }
        }
    }
   public static  MyOrderAdaper orderAdaper;
   public static  MyPinglunAdaper pinglunAdaper;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_me, container, false);
        et_username_me = view.findViewById(R.id.et_username_me);
        et_password_me = view.findViewById(R.id.et_password_me);
        et_phone_me = view.findViewById(R.id.et_phone_me);
        et_address_me = view.findViewById(R.id.et_address_me);
        btn_ok_me = view.findViewById(R.id.btn_ok_me);
        radioGroup = view.findViewById(R.id.rg_order_me);
        rv_order_bottom = view.findViewById(R.id.rv_order_bottom);
        tx_userid_me = view.findViewById(R.id.tx_userid_me) ;
        btn_adv = view.findViewById(R.id.btn_adv) ;
        context = this.getActivity();
        manager = this.getActivity().getSupportFragmentManager();
        queue = Volley.newRequestQueue(context);
        getUserByURL(Utils.urlBase+"and_getUserByUserId.do?id="+MainActivity.user_id);
        //获取用户头像
        new LoadImageTask().execute();
        btn_ok_me.setOnClickListener(v -> {
            User user = new User();
            int id = Integer.parseInt(tx_userid_me.getText().toString());
            user.setUser_id(id);
            user.setUsername(et_username_me.getText().toString());
            user.setUserpass(et_password_me.getText().toString());
            user.setMobilenum(et_phone_me.getText().toString());
            user.setAddress(et_address_me.getText().toString());
            updateUserByURL(Utils.urlBase+"and_updateUserByUserId.do",user,queue);
        });
        btn_adv.setOnClickListener(v -> {

//            //打开图库选择图片
            Intent intent = new Intent(Intent.ACTION_PICK,null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
            startActivityForResult(intent,2);
        });
        orderAdaper = new MyOrderAdaper();
        pinglunAdaper = new MyPinglunAdaper();
        radioGroup.check(R.id.rb_order_me);
        rv_order_bottom.setAdapter(orderAdaper);
        rv_order_bottom.setLayoutManager(new LinearLayoutManager(context));
        getOrderArrayList(Utils.urlBase+"and_getOrdersByUserId.do?id="+MainActivity.user_id);
        getPinglunArrayList(Utils.urlBase+"and_getPinglunByUserId.do?id="+MainActivity.user_id);
       radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
           @Override
           public void onCheckedChanged(RadioGroup group, int checkedId) {
               if(checkedId == R.id.rb_order_me){
                   rv_order_bottom.setAdapter(orderAdaper);
               }else if(checkedId == R.id.rb_comment_me){
                   rv_order_bottom.setAdapter(pinglunAdaper);
               }
           }
       });
        return view;
    }

    //接收选择的头像
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2 && resultCode == RESULT_OK) {
            //打开加载弹窗
            BasePopupView loadingDialog = new XPopup.Builder(getContext())
                    .asLoading("上传中")
                    .show();

            //转成File对象
            Uri imageUri = data.getData();
            File imageFile = null;
            try {
                imageFile = convertUriToFile(getContext(), imageUri);
                if (imageFile != null) {
                    Map<String,Object> map = new HashMap<>();
                    map.put("file",imageFile);
                    map.put("userId",MainActivity.user_id);
                    // 上传到服务器后的逻辑
                    new ImageUploadTask(result -> {
                        if (result.getBoolean("flag")){
                            //设置到图片
                            btn_adv.setImageURI(data.getData());
                            Toast.makeText(getContext(), "上传成功", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(getContext(), result.getString("msg"), Toast.LENGTH_SHORT).show();
                        }
                    }).execute(map);

                } else {
                    Toast.makeText(getContext(), "转换File对象失败。", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getContext(), "转换过程中发生错误：" + e.getMessage(), Toast.LENGTH_LONG).show();
            }
            //关闭加载弹窗
            loadingDialog.smartDismiss();
        }
    }


    public void getUserByURL(String url){
        Response.Listener listener1 = new Response.Listener() {
            @Override
            public void onResponse(Object o) {
                User user = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(),User.class);
                tx_userid_me.setText(user.getUser_id()+"");
                et_username_me.setText(user.getUsername());
                et_password_me.setText(user.getUserpass());
                et_phone_me.setText(user.getMobilenum());
                et_address_me.setText(user.getAddress());

            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyError.printStackTrace();
            }
        };
        JsonRequest request = new JsonObjectRequest(url,null,listener1,listener2);
        queue.add(request);
    }
    public static void updateUserByURL(String url,User user,RequestQueue queue){

        Response.Listener listener1 = new Response.Listener() {
            @Override
            public void onResponse(Object o) {
                try {
                    JSONObject obj = new JSONObject(o.toString());
                    if (context != null){
                        Toast.makeText(context,obj.getString("msg"),Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyError.printStackTrace();
            }
        };
        try {
            JSONObject object = new JSONObject(new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().toJson(user).toString());
            JsonRequest request = new JsonObjectRequest(url,object,listener1,listener2);
            queue.add(request);
        }catch (JSONException e){
           e.printStackTrace();
        }

    }
    public void setItemPriceByURL(String url,Order order,MyOrderAdaper.ViewHolder viewHolder){
        Response.Listener listener1 = new Response.Listener() {
            @Override
            public void onResponse(Object o) {
                Food food = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(),Food.class);

                viewHolder.tx_foodname_order_doneorder.setText(food.getFoodname()+" "+
                        food.getPrice()+"*"+order.getNum()+"="+food.getPrice()*order.getNum()+"元");
                setItemAddressByURL(Utils.urlBase+"and_getShopByShopId.do?id="+food.getShop_id()
                        ,viewHolder);
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonObjectRequest(url,null,listener1,listener2);
        queue.add(request);
    }
    public void setItemAddressByURL(String url,MyOrderAdaper.ViewHolder viewHolder){
        Response.Listener listener1 = new Response.Listener() {
            @Override
            public void onResponse(Object o) {
                Shop shop = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(),Shop.class);
                viewHolder.tx_shop_doneorder.setText(shop.getShopname()+" "+shop.getAddress());
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonObjectRequest(url,null,listener1,listener2);
        queue.add(request);
    }
    public void setItemFoodMsg(String url,MyPinglunAdaper.ViewHolder viewHolder){
        Response.Listener listener1 = new Response.Listener() {
            @Override
            public void onResponse(Object o) {
                Food food = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(),Food.class);
                viewHolder.tx_food_donepinglun.setText(food.getFoodname()+" 单价："
                        +food.getPrice()+"元");
                viewHolder.tx_shop_donepinglun.setText("("+food.getShopname()+")");
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonObjectRequest(url,null,listener1,listener2);
        queue.add(request);
    }
    //获取用户头像
    public static Bitmap getUserAvatar() {
        String s = OkHttpClientUtil.doGet(Utils.urlBase + "and_get_advatar.do?userId=" + MainActivity.user_id);
        try {
            JSONObject res = new JSONObject(s);
            System.out.println("请求头像:" + res);
            if (res.getBoolean("flag")){
                if (StringUtils.isBlank(res.getString("data"))){
                    return null;
                }
                String imageUrl = Utils.urlBase + "uploads/" + res.getString("data");
                //加载网络图片
                URL url = new URL(imageUrl);
                return BitmapFactory.decodeStream(url.openConnection().getInputStream());
            }else{
                Toast.makeText(context,res.getString("msg"),Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;

    }

    private class LoadImageTask extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... strings) {
            return getUserAvatar();
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (bitmap != null){
                btn_adv.setImageBitmap(bitmap);
            }
        }
    }


        //获取已完成订单网络数据
    public static void getOrderArrayList(String url){
        Response.Listener listener1 = new Response.Listener(){

            @Override
            public void onResponse(Object o) {
                orderList = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a")
                        .create().fromJson(o.toString(),new TypeToken<ArrayList<Order>>(){}.getType());
                orderAdaper.notifyDataSetChanged();
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonArrayRequest(url,listener1,listener2);
        queue.add(request);
    }
    public static void getPinglunArrayList(String url){
        Response.Listener listener1 = new Response.Listener(){

            @Override
            public void onResponse(Object o) {
                pinglunList = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create()
                        .fromJson(o.toString(),new TypeToken<ArrayList<Order>>(){}.getType());
                pinglunAdaper.notifyDataSetChanged();
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonArrayRequest(url,listener1,listener2);
        queue.add(request);
    }
    public void deletePinglunByURL(String url){
        Response.Listener listener1 = new Response.Listener() {
            @Override
            public void onResponse(Object o) {
                try {
                    JSONObject obj = new JSONObject(o.toString());
                    Toast.makeText(context,obj.getString("msg"),Toast.LENGTH_LONG).show();
                    getOrderArrayList(Utils.urlBase+"and_getOrdersByUserId.do?id="+MainActivity.user_id);
                    getPinglunArrayList(Utils.urlBase+"and_getPinglunByUserId.do?id="+MainActivity.user_id);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonObjectRequest(url,null,listener1,listener2);
        queue.add(request);
    }

    // 将Uri转换为File对象的方法
    private File convertUriToFile(Context context, Uri uri) throws IOException {
        InputStream inputStream = context.getContentResolver().openInputStream(uri);
        if (inputStream == null) {
            return null;
        }

        // 使用临时文件或在应用私有目录创建文件
        File tempFile = File.createTempFile("tempImage", ".jpg", context.getCacheDir());

        OutputStream outputStream = new FileOutputStream(tempFile);

        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        outputStream.flush();
        outputStream.close();
        inputStream.close();

        return tempFile;
    }
}